import sys
import codecs
import markdown as mark
# from pyquery import PyQuery as pq
import re
from os import getcwd
import shutil

fileName = getcwd() + '/document.md'
template = getcwd() + '/doc.html'
def parse(fileName):
	with codecs.open(fileName,'r',encoding='utf-8') as f:
		data = mark.markdown(f.read())
	content = re.split(r'<h1>.*</h1>',data)
	title = re.findall(r'<h1>.*</h1>',data)
 # 	sidebar = ''' 
	# <h5></h5>
	# <ul>
	# 	<li><a href="www.baidu.com"></a></li>
	# 	<li><a href="www.baidu.com"></a></li>
	# </ul>
	#'''
	sidebar = ''
	i = 0
	for x in title:
		h1 = x.replace('<h1>','').replace('</h1>','')
		sidebar += '<h5><a href="/doc/{}.html">'.format(i) + h1 + '</a></h5>'
		i += 1
	i = 0
	for x in title:
		h1 = x.replace('<h1>','').replace('</h1>','')
		with codecs.open(template,'r',encoding='utf-8') as f:
			data = f.read()
		data = data.replace('{{sidebar}}',sidebar)
		data = data.replace('{{content}}',content[i+1])
		data = data.replace('{{title}}',h1)
		output = getcwd() + '/doc/' + str(i) + '.html'
		f = codecs.open(output,'w+',encoding='utf-8')
		f.write(data)
		f.close()
		i += 1

	fromFile = getcwd() + '/doc/0.html'
	toFile = getcwd() + '/document.html'
	shutil.copy(fromFile,toFile)


if __name__ == '__main__':
	# fileName = sys.argv[1]
	fileName = getcwd() + '/document.md'
	parse(fileName)

